/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sys.screen;

import java.awt.Color;
import java.awt.Component;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import sys.bean.UsuarioBean;
import sys.dao.UsuarioDao;
import sys.utils.LetterUpper;
import sys.utils.Mensagens;
import static sys.utils.Utils.escClose;

/**
 *
 * @author Administrador
 */
public class UIPesquisaUsuarios extends javax.swing.JDialog {

    /**
     * Creates new form UIPesquisaUsuarios
     *
     * @param parent
     * @param modal
     */
    public UIPesquisaUsuarios(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        UIManager.put("Table.alternateRowColor", new java.awt.Color(230, 255, 255));
        setLocationRelativeTo(null);
        escClose(this);
    }

    private void carregaCadastroUsuario() {
        if (tabela.getSelectedRow() < 0) {
            Mensagens.msgAtencao("selecione usuario");
        } else {
            try {
                //tenta incluir usuário, se ja exixtir cai no catch onde apenas carrega os dados
                UsuarioDao.incluir(retornaObjeto());

                UICadastroUsuario cadUsuario = new UICadastroUsuario(this, true);

                cadUsuario.carregaDadosUsuario(tabela.getValueAt(tabela.getSelectedRow(), 0).toString());
                cadUsuario.carregaPermissoesUsuario(tabela.getValueAt(tabela.getSelectedRow(), 0).toString());
                cadUsuario.setVisible(true);

            } catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException ex) {

                UICadastroUsuario cadUsuario = new UICadastroUsuario(this, true);

                cadUsuario.carregaDadosUsuario(tabela.getValueAt(tabela.getSelectedRow(), 0).toString());
                cadUsuario.carregaPermissoesUsuario(tabela.getValueAt(tabela.getSelectedRow(), 0).toString());
                cadUsuario.setVisible(true);

            } catch (SQLException e) {

            }

        }
    }

    private UsuarioBean retornaObjeto() {
        UsuarioBean usuario = new UsuarioBean();

        usuario.setCodigo(tabela.getValueAt(tabela.getSelectedRow(), 0).toString());
        usuario.setNome(tabela.getValueAt(tabela.getSelectedRow(), 1).toString());
        usuario.setTipo(tabela.getValueAt(tabela.getSelectedRow(), 2).toString());
        usuario.setSituacao(tabela.getValueAt(tabela.getSelectedRow(), 3).toString());

        return usuario;
    }

    public void atualizaTabela() {
        DefaultTableModel modelo = (DefaultTableModel) tabela.getModel();
        modelo.setNumRows(0);

        try {
            for (UsuarioBean usuario : UsuarioDao.listaUsuarios(txNomeUsuario.getText())) {
                modelo.addRow(new Object[]{
                    usuario.getCodigo(), usuario.getNome(), usuario.getTipo(), usuario.getSituacao()
                });
            }

            tabela.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                    String ref = table.getValueAt(row, 3).toString();

                    switch (ref) {
                        case "ATIVO":
                            setForeground(Color.BLUE);
                            break;
                        case "INATIVO":
                            setForeground(Color.RED);
                            break;
                        default:
                            setForeground(null);
                            break;
                    }
                    return this;
                }
            });

        } catch (SQLException | IOException ex) {
            Mensagens.msgErro("erro ao atualizar usuários\n" + ex.getMessage());
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txNomeUsuario = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        btnAlterar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        btnBuscar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("PESQUISA USUÁRIOS");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        txNomeUsuario.setDocument(new LetterUpper());
        txNomeUsuario.setBackground(new java.awt.Color(245, 245, 245));
        txNomeUsuario.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        txNomeUsuario.setForeground(new java.awt.Color(51, 51, 255));
        txNomeUsuario.setBorder(null);
        txNomeUsuario.setPreferredSize(new java.awt.Dimension(0, 25));
        txNomeUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txNomeUsuarioActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel1.setText("NOME:");

        tabela.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        tabela.setForeground(new java.awt.Color(51, 102, 255));
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "CODIGO", "NOME", "FUNÇÃO", "SITUACAO"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabela.setGridColor(new java.awt.Color(204, 204, 204));
        tabela.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tabela);
        if (tabela.getColumnModel().getColumnCount() > 0) {
            tabela.getColumnModel().getColumn(0).setPreferredWidth(20);
            tabela.getColumnModel().getColumn(1).setPreferredWidth(150);
        }

        jPanel2.setBackground(new java.awt.Color(245, 245, 245));

        btnAlterar.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/edit.png"))); // NOI18N
        btnAlterar.setText("ALTERAR");
        btnAlterar.setPreferredSize(new java.awt.Dimension(120, 30));
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        jPanel2.add(btnAlterar);

        btnSair.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/sair.png"))); // NOI18N
        btnSair.setText("SAIR");
        btnSair.setPreferredSize(new java.awt.Dimension(120, 30));
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });
        jPanel2.add(btnSair);

        btnBuscar.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/find.png"))); // NOI18N
        btnBuscar.setText("BUSCAR");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txNomeUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnBuscar)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txNomeUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txNomeUsuarioActionPerformed
        final BarraProgresso pb = new BarraProgresso(this);
        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                pb.gerarJanela();

                pb.lbDescricao.setText("CARREGANDO PERMISSOES, AGUARDE...");
                atualizaTabela();
                return null;
            }

            @Override
            protected void done() {
                pb.fechar();
            }
        };
        worker.execute();
    }//GEN-LAST:event_txNomeUsuarioActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed

        final BarraProgresso pb = new BarraProgresso(this);
        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                pb.gerarJanela();

                pb.lbDescricao.setText("CARREGANDO PERMISSOES, AGUARDE...");
                atualizaTabela();
                return null;
            }

            @Override
            protected void done() {
                pb.fechar();
            }
        };
        worker.execute();
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        final BarraProgresso pb = new BarraProgresso(this);
        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                pb.gerarJanela();

                pb.lbDescricao.setText("CARREGANDO PERMISSOES, AGUARDE...");
                carregaCadastroUsuario();

                return null;
            }

            @Override
            protected void done() {
                pb.fechar();
            }
        };
        worker.execute();
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnSair;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabela;
    private javax.swing.JTextField txNomeUsuario;
    // End of variables declaration//GEN-END:variables
}
